import React, { useEffect, useRef, useState } from 'react';
import { Tabs, TabsProps, message } from 'antd';
import Modals from '@/components/modals/Modals';
import { GetMcpServersListItem } from '@/common';
import { SvgIcon } from '@/components/icon';

interface Props {
  open: boolean;
  onOk: () => void;
  onCancel: () => void;
  value?: GetMcpServersListItem;
}

const index = ({ value, ...props }: Props) => {
  const tabsItems: TabsProps['items'] = [
    {
      key: '1',
      label: <div className="text-sm">Streamable HTTP</div>,
    },
    {
      key: '2',
      label: <div className="text-sm">SSE</div>,
    },
  ];
  const [tabsValue, setTabsValue] = useState('1');

  const { url, jsonConfig } = (() => {
    const currentOrigin = window.location.origin;

    const processConfig = (config: any) => {
      if (!config || typeof config !== 'object') return config;

      const processedConfig = JSON.parse(JSON.stringify(config));

      const processUrls = (obj: any) => {
        for (const key in obj) {
          if (typeof obj[key] === 'object' && obj[key] !== null) {
            processUrls(obj[key]);
          } else if (key === 'url' && typeof obj[key] === 'string') {
            if (!obj[key].startsWith('http://') && !obj[key].startsWith('https://') && !obj[key].startsWith(currentOrigin)) {
              obj[key] = `${currentOrigin}${obj[key]}`;
            }
          }
        }
      };

      processUrls(processedConfig);
      return processedConfig;
    };

    if (tabsValue === '1') {
      const originalUrl = value?.mcpServerConfig?.StreamableHttp?.url
      const url = originalUrl ?
        (originalUrl.startsWith('http://') || originalUrl.startsWith('https://') || originalUrl.startsWith(currentOrigin) ?
          originalUrl : `${currentOrigin}${originalUrl}`) : '';
      const jsonConfig = processConfig(value?.mcpServerConfig?.StreamableHttp?.config)

      return {
        url,
        jsonConfig
      };
    }
    const originalUrl = value?.mcpServerConfig?.SSE?.url
    const url = originalUrl ?
      (originalUrl.startsWith('http://') || originalUrl.startsWith('https://') || originalUrl.startsWith(currentOrigin) ?
        originalUrl : `${currentOrigin}${originalUrl}`) : '';
    const jsonConfig = processConfig(value?.mcpServerConfig?.SSE?.config)
    return {
      url,
      jsonConfig
    };
  })();

  const handleCopyForm = (serviceValue: any) => {
    if (serviceValue) {
      const textArea = document.createElement('textarea');
      textArea.value = serviceValue;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand('copy');
        message.success('复制成功！');
      } catch {
        message.error('复制失败，请手动复制');
      }
      document.body.removeChild(textArea);
    } else {
      message.warning('没有内容可复制');
    }
  };

  const ModalsTitle = () => {
    return (
      <div>
        <div className="text-base font-bold text-text-5">服务详情</div>
      </div>
    );
  };

  return (
    <Modals {...props} width={720} title={<ModalsTitle />} footerCancelHidden footer={null}>
      <Tabs items={tabsItems} activeKey={tabsValue} onChange={(key) => setTabsValue(key)} />
      <div className='flex flex-col gap-4 pb-6'>
        <div
          className='flex flex-col gap-2'
        >
          <span className='text-sm text-text-4'>MCP 地址</span>
          <div
            className='border border-line-2 rounded-md px-4 bg-fill-1 h-10 flex items-center justify-between'
          >
            <span>
              {url}
            </span>
            <span
              onClick={() => {
                const serviceValue = url;
                handleCopyForm(serviceValue);
              }}
              className='flex items-center cursor-pointer text-[var(--brand-color)] gap-1'
            >
              <SvgIcon icon="singlecopy" size={16}></SvgIcon>
              复制
            </span>
          </div>
        </div>
        <div
          className='border border-line-2 rounded-md'
        >
          <div
            className='flex items-center justify-between px-4 bg-fill-1 h-10'
          >
            <span className='text-sm text-text-4'>MCP json配置</span>
            <span
              onClick={() => {
                const serviceValue = JSON.stringify(jsonConfig, null, 2);
                handleCopyForm(serviceValue);
              }}
              className='flex items-center cursor-pointer text-[var(--brand-color)] gap-1'
            >
              <SvgIcon icon="singlecopy" size={16}></SvgIcon>
              复制
            </span>
          </div>
          <pre className="bg-white p-5 rounded text-xs overflow-x-auto">{typeof jsonConfig === 'string' ? jsonConfig : JSON.stringify(jsonConfig, null, 2)}</pre>
        </div>
      </div>
    </Modals>
  );
};

export default index;
